package com.example.web.websocket.handle;

import com.alibaba.fastjson.JSON;
import com.example.web.websocket.entity.ReceiveObject;
import com.example.web.websocket.entity.RelayObject;
import com.example.web.websocket.entity.User;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * Created by YangGang on 2021/8/2 16:11。
 */
public class MessageHandle {
    private static MessageHandle messageHandle = new MessageHandle();
    private static Set<RelayObject> queue = new CopyOnWriteArraySet<>();

    private MessageHandle() {
    }

    public static MessageHandle getHandle() {
        return messageHandle;
    }

    /**
     * 检查消息队列中是否有消息需要接受
     *
     * @param user
     */
    public void checkMessageQueue(User user) {
        List<RelayObject> collect = new ArrayList<>();
        queue.forEach(q -> {
            if (user.getKey().equals(q.getToKey())) {
                collect.add(q);
            }
        });
        if (collect.size() > 0) {
            collect.forEach(x -> {
                try {
                    user.getSession().getBasicRemote().sendText(JSON.toJSONString(x));
                    queue.remove(x);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
        }
    }

    public void parseMessage(String messageJson) {
        ReceiveObject receiveObject = JSON.parseObject(messageJson, ReceiveObject.class);
        if (receiveObject.getToKey() != null) {
            relayToKey(receiveObject);
        }
        if (receiveObject.getToGroup() != null) {
            relayToGroup(receiveObject);
        }
    }

    //转送消息到group
    public void relayToGroup(ReceiveObject receiveObject) {
        //List<User> userList = UserHandle.findGroupUser(receiveObject.getToGroup());

    }

    //转送消息到key
    public void relayToKey(ReceiveObject receive) {
        RelayObject relay = new RelayObject(receive.getSourceKey(), receive.getToKey(), receive.getData());
        User user = UserHandle.getHandle().findUser(receive.getToKey());
        if (user != null) {
            try {
                user.getSession().getBasicRemote().sendText(JSON.toJSONString(relay));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            //user不存在就保存到队列中
            queue.add(relay);
        }
    }


}
